package io.shallwe._admin.role;

import java.util.LinkedHashMap;
import java.util.List;

import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Page;

import io.shallwe._admin.permission.PermissionAdminService;
import io.shallwe.common.controller.BaseController;
import io.shallwe.common.model.Permission;
import io.shallwe.common.model.Role;

public class RoleAdminController extends BaseController {

	@Inject
	RoleAdminService roleService;
	
	@Inject
	PermissionAdminService permissionService;
	
	public void index() {
		render("role.html");
	}
	
	public void list() {
		Integer offset = getParaToInt("offset",1);
        Integer pageSize = getParaToInt("pageSize",100);
		renderJson(roleService.paginate(offset,pageSize));
	}
	
	public void add() {
		render("add_edit.html");
	}
	
	@Before(RoleAdminValidator.class)
	public void save() {
		Role role = getBean(Role.class);
		Ret ret = roleService.save(role);
		renderJson(ret);
	}
	
	public void edit() {
		keepPara("p");	// 保持住分页的页号，便于在 ajax 提交后跳转到当前数据所在的页
		Role role = roleService.findById(getPara("id"));
		setAttr("role", role);
		render("add_edit.html");
	}

	/**
	 * 提交修改
	 */
	@Before(RoleAdminValidator.class)
	public void update() {
		Role role = getBean(Role.class);
		Ret ret = roleService.update(role);
		renderJson(ret);
	}

	public void delete() {
		Ret ret = roleService.delete(getPara("id"));
		renderJson(ret);
	}

	/**
	 * 分配权限
	 */
	public void assignPermissions() {
		Role role = roleService.findById(getPara("id"));
		List<Permission> permissionList = permissionService.getAllPermissions();
		roleService.markAssignedPermissions(role, permissionList);
		LinkedHashMap<String, List<Permission>> permissionMap = roleService.groupByController(permissionList);

		setAttr("role", role);
		setAttr("permissionMap", permissionMap);
		render("assign_permissions.html");
	}

	/**
	 * 添加权限
	 */
	public void addPermission() {
		Ret ret = roleService.addPermission(getPara("roleId"), getPara("permissionId"));
		renderJson(ret);
	}

	/**
	 * 删除权限
	 */
	public void deletePermission() {
		Ret ret = roleService.deletePermission(getPara("roleId"), getPara("permissionId"));
		renderJson(ret);
	}
}
